package com.pnk087.hr.dao.jpa;

import com.pnk087.hr.dao.GenericDao;
import com.pnk087.hr.domain.Persistable;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.jpa.support.JpaDaoSupport;

/**
 * User: khanh
 * Date: 6/22/11 3:20 PM
 */
public class JpaGenericDao<T> extends JpaDaoSupport implements GenericDao<T> {

   private final Class<T> persistentClass;

   public JpaGenericDao(final Class<T> persistentClass) {
      this.persistentClass = persistentClass;
   }

   public T findById(final Long id) {
      T result = getJpaTemplate().find(this.persistentClass, id);
      if (result == null) {
         throw new ObjectRetrievalFailureException(persistentClass, id);
      }
      return result;
   }

   public void remove(final Long id) {
      getJpaTemplate().remove(this.findById(id));
   }

   public void save(final T object) {
      if (((Persistable) object).getId() != null) {
         getJpaTemplate().merge(object);
      } else {
         getJpaTemplate().persist(object);
      }
   }
}
